<?php

namespace app\admin\command;

use fast\Http;
use think\console\Input;
use think\console\Output;
use think\console\Command;
use think\console\input\Option;
use app\admin\model\wanlshop\Goods;
use addons\wanlshop\library\WanlSdk\Common;
use app\api\service\wanlshop\Goods as GoodsService;

class Sync extends Command
{
    protected function configure()
    {
        $this->setName('sync')
            ->addOption('page', null, Option::VALUE_OPTIONAL, '页码')
            ->setDescription('sync goods list data');
    }

    protected function execute(Input $input, Output $output)
    {
        date_default_timezone_set('PRC');
        ini_set('memory_limit', '-1');
        set_time_limit(0);

        $date = date('Y-m-d H:i:s');
        $output->writeln("开始获取数据，开始时间: $date");
        $page = $input->getOption('page');
        $size = 100;
        $starttime = microtime(true);
        $redis = Common::redis();
        if (!$page) {
            if ($redis->exists('syncPage')) {
                $page = $redis->get('syncPage');
            } else {
                $page = floor(Goods::order('id', 'desc')->limit(1)->value('id') / 100);
            }
        }

        $tryNum = 1;
        $goodsService = new GoodsService();
        while ($page) {

            $params = [
                'pageNo' => $page,
                'pageSize' => $size,
//                'is_sort' => 1,
//                'goodName' => "单拍不发货-森林棠品牌礼品袋 只拍礼品袋不发货(七天无理由退货退款|最迟发货时间:2024-01-11 00:01:02)"
            ];

            //测试渠道号：DONGHUOMUSZ
            // header
            $header = [
//                'channelType:' . 'DONGHUOMUSZ',
                'channelType:' . 'DONGHUOMU',
                'md5:' . $this->getSign($params)
            ];

            // 额外参数
            $option = [
                CURLOPT_HTTPHEADER => $header,
                CURLOPT_POSTFIELDS => http_build_query($params),
                CURLOPT_POST => 1
            ];

            //同步商品数据
//            $resp = Http::post("https://uat.api.weipinshang.net/mcang/Mcang/getGoodsList", $params, $option);
            $resp = Http::post("https://api.weipinshang.net/mcang/Mcang/getGoodsList", $params, $option);
            //var_dump(json_decode($resp, true));
            var_dump("页码：" . $page);
            var_dump("重试次数：" . $tryNum);
            // 添加数据到数据库
            $list = json_decode($resp, true);
            if (isset($list['code']) && $list['code'] != 0) {
                if ($tryNum > 100) {
                    return;
                }
                $output->writeln("请求数据失败,msg:{$list['msg']}");
                $output->writeln("第 {$page} 页获取数据失败，重试第 ｛ $tryNum ｝ 次");
                ++$tryNum;
                sleep(5);
            }
            if (isset($list['data']['list']) && !empty($list['data']['list'])) {
                $al = $goodsService->insGoods($list['data']['list'], $output, $page, $size);
                if ($al) {
                    $output->writeln("第 {$page} 页新增数据完毕");
                    ++$page;
                    $tryNum = 1;
                }
            } else {
                if ($tryNum > 100) {
                    return;
                }
                $endtime = microtime(true);
                $ex = number_format($endtime - $starttime, 2);
                $output->writeln("第 {$page} 页获取数据失败，重试第 ｛ $tryNum ｝ 次");
                $output->writeln("无数据，总耗时:$ex 秒");
                ++$tryNum;
                sleep(5);
                //return;
            }
            $redis->set('syncPage', $page);
            $output->writeln("set redis key --$page");
        }
    }

    protected function getSign($params = [])
    {
        $query = [];
        ksort($params);
        foreach ($params as $key => $val) {
            $query[] = $key . "=" . $val;
        }
        $data = implode('&', $query);
//        return strtolower(md5($data . "DONGHUOMUSZ" . "4e0f57288842aa18f236b45f72d1e2a8"));//测试
        return strtolower(md5($data . "DONGHUOMU" . "ca69a0343ac66303f01d172bb86bd65c"));//正式
    }
}